<template>
  <div class="order-view">
    <a-page-header title="我的订单" />
    <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
      <a-tab-pane key="all" tab="全部订单">
        <a-table
          :dataSource="filteredOrders"
          :columns="columns"
          rowKey="id"
          :loading="loading"
          :pagination="pagination"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'product'">

              <div class="product-info">
                <a-image
                  :src="record.coverImg"
                  :width="60"
                  :height="60"
                  :preview="false"
                  class="product-image"
                />

                <div class="product-details">
                  <div class="product-name">{{ record.title }}</div>
                  <div class="product-spec">规格：{{ record.specify }}</div>
                  <div class="product-quantity">数量：1</div>
                </div>
              </div>
            </template>
            <template v-else-if="column.key === 'amount'">
              <span class="amount">¥{{ record.price?.toFixed(2) }}</span>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button
                  v-if="record.status === 1"
                  type="primary"
                  size="small"
                  @click="handlePay(record)"
                >
                  立即付款
                </a-button>
                <a-button
                  v-if="record.status === 2"
                  size="small"
                  @click="handleViewLogistics(record)"
                >
                  查看物流
                </a-button>
                <a-button
                  v-if="record.status === 3"
                  type="primary"
                  size="small"
                  @click="handleReview(record)"
                >
                  评价
                </a-button>
                <a-button
                  v-if="record.status === 4"
                  size="small"
                  @click="handleBuyAgain(record)"
                >
                  再次购买
                </a-button>
                <a-button size="small" @click="handleViewDetail(record)">
                  查看详情
                </a-button>
                <a-button
                  v-if="record.status === 1"
                  size="small"
                  danger
                  @click="handleCancel(record)"
                >
                  取消订单
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="1" tab="待付款">
        <a-table
          :dataSource="filteredOrders"
          :columns="columns"
          rowKey="id"
          :loading="loading"
          :pagination="pagination"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'product'">
              <div class="product-info">
                <a-image
                  :src="record.coverImg"
                  :width="60"
                  :height="60"
                  :preview="false"
                  class="product-image"
                />
                <div class="product-details">
                  <div class="product-name">{{ record.title }}</div>
                  <div class="product-spec">规格：{{ record.specify }}</div>
                  <div class="product-quantity">数量：1</div>
                </div>
              </div>
            </template>
            <template v-else-if="column.key === 'amount'">
              <span class="amount">¥{{ record.price?.toFixed(2) }}</span>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button
                  type="primary"
                  size="small"
                  @click="handlePay(record)"
                >
                  立即付款
                </a-button>
                <a-button size="small" @click="handleViewDetail(record)">
                  查看详情
                </a-button>
                <a-button size="small" danger @click="handleCancel(record)">
                  取消订单
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="2" tab="待发货">
        <a-table
          :dataSource="filteredOrders"
          :columns="columns"
          rowKey="id"
          :loading="loading"
          :pagination="pagination"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'product'">
              <div class="product-info">
                <a-image
                  :src="record.coverImg"
                  :width="60"
                  :height="60"
                  :preview="false"
                  class="product-image"
                />
                <div class="product-details">
                  <div class="product-name">{{ record.title }}</div>
                  <div class="product-spec">规格：{{ record.specify }}</div>
                  <div class="product-quantity">数量：1</div>
                </div>
              </div>
            </template>
            <template v-else-if="column.key === 'amount'">
              <span class="amount">¥{{ record.price?.toFixed(2) }}</span>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button size="small" @click="handleViewLogistics(record)">
                  查看物流
                </a-button>
                <a-button size="small" @click="handleViewDetail(record)">
                  查看详情
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="3" tab="待评价">
        <a-table
          :dataSource="filteredOrders"
          :columns="columns"
          rowKey="id"
          :loading="loading"
          :pagination="pagination"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'product'">
              <div class="product-info">
                <a-image
                  :src="record.coverImg"
                  :width="60"
                  :height="60"
                  :preview="false"
                  class="product-image"
                />
                <div class="product-details">
                  <div class="product-name">{{ record.title }}</div>
                  <div class="product-spec">规格：{{ record.specify }}</div>
                  <div class="product-quantity">数量：1</div>
                </div>
              </div>
            </template>
            <template v-else-if="column.key === 'amount'">
              <span class="amount">¥{{ record.price?.toFixed(2) }}</span>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button
                  type="primary"
                  size="small"
                  @click="handleReview(record)"
                >
                  评价
                </a-button>
                <a-button size="small" @click="handleViewDetail(record)">
                  查看详情
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-tab-pane>
    </a-tabs>

    <!-- 评价弹窗 -->
    <a-modal
      v-model:open="reviewModalVisible"
      title="商品评价"
      @ok="handleReviewSubmit"
      @cancel="handleReviewCancel"
      width="500px"
    >
      <a-form :model="reviewForm" layout="vertical">
        <a-form-item label="评分">
          <a-rate v-model:value="reviewForm.rating" />
        </a-form-item>
        <a-form-item label="评价内容">
          <a-textarea
            v-model:value="reviewForm.content"
            :rows="4"
            placeholder="请分享您的使用体验..."
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { message } from "ant-design-vue";
import { listOrdersVoByPage } from "@/api/ordersController";
import {addCartProducts} from "@/api/cartController.ts";
import router from "@/router";

interface OrderItem {
  id: string;
  orderNo: string;
  title: string;
  coverImg: string;
  specify: string;
  quantity: number;
  price: number;
  status: number; // 1待付款/2待发货/3待评价/4已完成/5已取消
  createTime: string;
  payTime?: string;
  shipTime?: string;
  completeTime?: string;
}

interface ReviewForm {
  rating: number;
  content: string;
}

const activeTab = ref("all");
const loading = ref(false);
const reviewModalVisible = ref(false);
const currentOrder = ref<OrderItem | null>(null);
const reviewForm = ref<ReviewForm>({
  rating: 5,
  content: "",
});

// 模拟订单数据
const orders = ref<OrderItem[]>([
  {
    id: "1",
    orderNo: "ORD20241201001",
    title: "iPhone 15 Pro Max",
    coverImg: "https://via.placeholder.com/60x60/007AFF/FFFFFF?text=iPhone",
    specify: "256GB 深空黑色",
    quantity: 1,
    price: 9999.0,
    status: 1, // 待付款
    createTime: "2024-12-01 10:30:00",
  },
  {
    id: "2",
    orderNo: "ORD20241128002",
    title: "MacBook Pro 14英寸",
    coverImg: "https://via.placeholder.com/60x60/34C759/FFFFFF?text=MacBook",
    specify: "M3 Pro 1TB SSD",
    quantity: 1,
    price: 18999.0,
    status: 2, // 待发货
    createTime: "2024-11-28 14:20:00",
    payTime: "2024-11-28 14:25:00",
  },
  {
    id: "3",
    orderNo: "ORD20241125003",
    title: "AirPods Pro",
    coverImg: "https://via.placeholder.com/60x60/FF9500/FFFFFF?text=AirPods",
    specify: "第二代 主动降噪",
    quantity: 2,
    price: 3998.0,
    status: 3, // 待评价
    createTime: "2024-11-25 09:15:00",
    payTime: "2024-11-25 09:20:00",
    shipTime: "2024-11-26 16:30:00",
  },
  {
    id: "4",
    orderNo: "ORD20241120004",
    title: "iPad Air",
    coverImg: "https://via.placeholder.com/60x60/5856D6/FFFFFF?text=iPad",
    specify: "64GB WiFi版",
    quantity: 1,
    price: 4799.0,
    status: 4, // 已完成
    createTime: "2024-11-20 11:45:00",
    payTime: "2024-11-20 11:50:00",
    shipTime: "2024-11-21 10:00:00",
    completeTime: "2024-11-23 15:30:00",
  },
  {
    id: "5",
    orderNo: "ORD20241115005",
    title: "Apple Watch Series 9",
    coverImg: "https://via.placeholder.com/60x60/FF3B30/FFFFFF?text=Watch",
    specify: "45mm GPS版",
    quantity: 1,
    price: 3299.0,
    status: 5, // 已取消
    createTime: "2024-11-15 16:20:00",
  },
]);

const columns = [
  { title: "订单号", dataIndex: "id", key: "id", width: 150 },
  { title: "商品", dataIndex: "product", key: "product", width: 300 },
  { title: "金额", dataIndex: "price", key: "amount", width: 120 },
  { title: "状态", dataIndex: "status", key: "status", width: 100 },
  { title: "操作", key: "action", width: 200 },
];

const pagination = {
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
};

const dataList = ref<any[]>([]);
const params = ref<API.Orders>({});
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await listOrdersVoByPage(params.value);
    if (res.data.data && res.data.code === 0) {
      dataList.value = res.data.data.records;
      pagination.total = res.data.data.total || 0;
    } else {
      message.error("获取数据失败!");
    }
  } catch (error) {
    message.error("获取数据出错!");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchData();
});

// 根据当前标签页过滤订单
const filteredOrders = computed(() => {
  if (activeTab.value === "all") {
    return dataList.value.length > 0 ? dataList.value : orders.value;
  }

  // 直接根据数字状态过滤
  const statusNumber = parseInt(activeTab.value);
  return (dataList.value.length > 0 ? dataList.value : orders.value).filter(
    (order) => order.status === statusNumber
  );
});

// 获取状态颜色
const getStatusColor = (status: number) => {
  const colorMap: Record<number, string> = {
    1: "orange", // 待付款
    2: "blue", // 待发货
    3: "purple", // 待评价
    4: "green", // 已完成
    5: "red", // 已取消
  };
  return colorMap[status] || "default";
};

// 获取状态文本
const getStatusText = (status: number) => {
  const textMap: Record<number, string> = {
    1: "待付款",
    2: "待发货",
    3: "待评价",
    4: "已完成",
    5: "已取消",
  };
  return textMap[status] || "未知状态";
};

// 标签页切换
const handleTabChange = (key: string) => {
  activeTab.value = key;
  pagination.current = 1;
};

// 立即付款
const handlePay = (order: OrderItem) => {
  router.push({
    path: `/checkout/${order.productId}`,
  });
  message.success(`正在跳转到支付页面，订单号：${order.id}`);
  // 这里可以跳转到支付页面
};

// 查看物流
const handleViewLogistics = (order: OrderItem) => {
  message.info(`查看物流信息，订单号：${order.orderNo}`);
  // 这里可以打开物流详情弹窗
};

// 评价
const handleReview = (order: OrderItem) => {
  currentOrder.value = order;
  reviewModalVisible.value = true;
};

// 再次购买
const handleBuyAgain =async (order: API.Orders) => {
  const param =  {
    productId:order.productId
  }
  const res =await addCartProducts(param)
  if(res.data.code===0 &&res.data.data){
    message.success(`已将 ${order.title} 加入购物车`);
  }else{
    message.error("添加失败!")
  }
};

// 查看详情
const handleViewDetail = (order:  API.Orders) => {
  router.push({
    path: `/product/${order.productId}`,
  });
  message.info(`查看订单详情，订单号：${order.id}`);
};

// 取消订单
const handleCancel = (order: OrderItem) => {
  message.warning(`确认取消订单 ${order.orderNo}？`);
  // 这里可以显示确认弹窗
};

// 提交评价
const handleReviewSubmit = () => {
  if (!reviewForm.value.content.trim()) {
    message.error("请填写评价内容");
    return;
  }

  if (currentOrder.value) {
    // 更新订单状态
    const order = orders.value.find((o) => o.id === currentOrder.value?.id);
    if (order) {
      order.status = 4; // 更新为已完成
    }
    message.success("评价提交成功！");
    reviewModalVisible.value = false;
    resetReviewForm();
  }
};

// 取消评价
const handleReviewCancel = () => {
  reviewModalVisible.value = false;
  resetReviewForm();
};

// 重置评价表单
const resetReviewForm = () => {
  reviewForm.value = {
    rating: 5,
    content: "",
  };
  currentOrder.value = null;
};
</script>

<style scoped>
.order-view {
  padding: 24px;
  width: 100%;
  max-width: 100%;
  margin: 0;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-image {
  border-radius: 4px;
  object-fit: cover;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.product-details {
  flex: 1;
}

.product-name {
  font-weight: 500;
  margin-bottom: 4px;
  color: #333;
  font-size: 14px;
}

.product-spec {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
}

.product-quantity {
  font-size: 12px;
  color: #999;
}

.amount {
  font-weight: 500;
  color: #ff4d4f;
}

:deep(.ant-table) {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

:deep(.ant-table-tbody > tr > td) {
  padding: 16px 8px;
}

:deep(.ant-tabs-nav) {
  margin-bottom: 16px;
}

:deep(.ant-tabs-content-holder) {
  margin-top: 16px;
}

:deep(.ant-page-header) {
  padding: 0 0 16px;
}

:deep(.ant-btn-primary) {
  background-color: #1890ff;
  border-color: #1890ff;
}

:deep(.ant-tag) {
  padding: 2px 8px;
  font-size: 12px;
  border-radius: 4px;
}
</style>
